<template lang="html">
  <div class="exam-card">
    <div class="card-header clearfix">
      <div class="time f-l">
        <i class="el-icon-time"></i>
        <span v-cloak>{{ hour }}:{{ min }}:{{ sec }}</span>
      </div>
      <div class="answer-card f-l m-l-20" @click="dialogVisible = true">
        <i class="el-icon-date"></i>
        <span>答题卡</span>
      </div>
      <div class="submit-paper f-r">
        <el-button type="primary" round @click="submitPaper">交卷</el-button>
      </div>
    </div>
    <div class="card-content">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>第{{ questionId + 1 }}题</span>
          <el-button
            style="float: right; padding: 3px 0"
            type="text"
            @click="nextQuestion"
            >下一题</el-button
          >
        </div>
        <div>
          <!-- 单选 -->
          <div class="q-single">
            <div class="question">
              {{ question[questionId].tm }}
            </div>
            <div class="answer">
              <div class="answer-item" v-for="(item, index) in select">
                <el-radio v-model="radio" :label="item.xx" @change="change">{{
                  item.xx
                }}</el-radio>
              </div>
            </div>
          </div>
        </div>
      </el-card>
    </div>
    <el-dialog title="答题卡" :visible.sync="dialogVisible" width="50%" @open="open">
      <el-button
        v-for="(item, index) in question"
        :key="index"
        :id="`list${index}`"
        :ref="`list${index}`"
        class="stu-answer-item"
        @click="clickAnswerCard(index)"
        >{{ index + 1 }}</el-button
      >
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";
import qs from "qs";
import { Message, MessageBox } from "element-ui";
export default {
  data() {
    return {
      dialogVisible: false, //初始化时默认不显示答题卡
      question: [{ tm: "" }], //添加初始值，因为axios异步,当数据没有加载时，会报错
      questionId: 0,
      select: [{ xx: "A" }, { xx: "B" }, { xx: "C" }, { xx: "D" }],
      radio: "",
      startTime: "",
      endTime: "",
      hour: 0,
      min: 0,
      sec: 0,
      timer: 0,
      onblurTime: 0,
      studentAnswer: [],
      answer: [],
      timu: [],
      score: 0,
    };
  },
  computed: {},
  methods: {
    //初始化试卷
    examInit() {
      let that = this; //全局函数里的this都指向window
      window.onblur = function () {
        that.onblurTime++;
        if (that.onblurTime == 3) {
          that.autoSubmitPaper(); //自动交卷
        } else if (that.onblurTime == 1) {
          MessageBox(
            "第一次提醒:考试期间不能离开此页面哦~提醒两次，第三次离开就会直接交卷了哦",
            "提示",
            {
              confirmButtonText: "确定",
              type: "error",
            }
          );
        } else {
          MessageBox(
            "第二次提醒:考试期间不能离开此页面哦~提醒两次，第三次离开就会直接交卷了哦",
            "提示",
            {
              confirmButtonText: "确定",
              type: "error",
            }
          );
        }
      };

      //倒计时
      this.timer = window.setInterval(() => {
        let timeLast = new Date(this.endTime).getTime() - new Date().getTime();
        let hour = parseInt(timeLast / (1000 * 60 * 60));
        let min = parseInt((timeLast % (1000 * 60 * 60)) / (1000 * 60));
        let sec = parseInt(
          ((timeLast % (1000 * 60 * 60)) % (1000 * 60)) / 1000
        );
        this.hour = hour < 10 ? "0" + hour : hour;
        this.min = min < 10 ? "0" + min : min;
        this.sec = sec < 10 ? "0" + sec : sec;

        if (this.hour == 0 && this.min == 0 && this.sec == 0) {
          window.clearInterval(this.timer);
          this.submitPaper();
        }
      }, 1000);
    },
    //单选框改变
    change() {
      this.studentAnswer[this.questionId] = this.radio; //把当前用户选择的选项存在下标对应的位置
    },
    //下一题
    nextQuestion() {
      this.studentAnswer[this.questionId] = this.radio; //把当前用户选择的选项存在下标对应的位置
      // console.log(this.studentAnswer);
      // console.log(this.radio);
      if (this.questionId >= 99) {
        Message.success({
          showClose: true,
          message: "这是最后一题啦",
          type: "success",
        });
        return;
      } else {
        this.questionId++;
        //如果当前题目已经被用户选择则显示用户选择的答案
        if (this.studentAnswer[this.questionId] != "") {
          // console.log(this.studentAnswer);
          this.radio = this.studentAnswer[this.questionId];
        } else {
          this.radio = ""; //否则把单选重置为空
        }
      }
    },
    //submitAxios //提交数据，传递数组
    submitAxios() {
      axios({
        method: "post",
        url: "/v1/students/receive",
        data: qs.stringify(
          {
            studentAnswer: this.studentAnswer, //用户选择的答案
            timu: this.timu, //题目
            answer: this.answer, //正确答案
            score: this.score, //成绩
          },
          { indices: false }
        ),
        headers: {
          "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
        },
      })
        .then((result) => {
          if (result.data.status == 200) {
            Message.success({
              showClose: true,
              message: "交卷成功",
              type: "success",
            });
            window.onblur = null; //交卷成功销毁
            this.$router.push("/studentHome/homepage");
          } else {
            Message.error({
              showClose: true,
              message: "交卷失败",
              type: "error",
            });
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //把正确答案，和题目存起来
    sureAnswer() {
      for (let a = 0; a < this.question.length; a++) {
        this.answer[a] = this.question[a].jd;
        this.timu[a] = this.question[a].tm;
      }
      //看看答对多少题
      let right = 0;
      for (let i = 0; i < this.answer.length; i++) {
        if (this.studentAnswer[i] == this.answer[i]) {
          //判断答案的正确与错误
          right++;
        }
      }
      this.score = right;
      // console.log(this.studentAnswer);
    },
    //自动交卷
    autoSubmitPaper() {
      this.sureAnswer();
      //判断用户是否答题
      if (this.studentAnswer.length != 0) {
        //是否交卷
        this.submitAxios();
      } else {
        Message.error({
          showClose: true,
          message: "请作答",
          type: "error",
        });
      }
    },
    //交卷
    submitPaper() {
      this.sureAnswer();
      //判断用户是否答题
      if (this.studentAnswer.length != 0) {
        //是否交卷
        this.$confirm("是否交卷?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            //确定交卷
            this.submitAxios();
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消",
            });
          });
      } else {
        Message.error({
          showClose: true,
          message: "请作答",
          type: "error",
        });
      }
    },
    open() {
      //Dialog 的内容是懒渲染的，即在第一次被打开之前，传入的默认 slot 不会被渲染到 DOM 上。
      //因此，如果需要执行 DOM 操作，或通过 ref 获取相应组件，请在 open 事件回调中进行。
      //解决Vue中使用Element 第一次打开el-dialog获取不到元素的解决办法
      this.$nextTick(function () {
        for (let a = 0; a < this.studentAnswer.length; a++) {
          //如果数组对应下标不为空，则把当前的答题卡题号按钮变色
          if (this.studentAnswer[a] != "") {
            // console.log(this.$refs[`list${a}`][0].$el);
            //vue中获取元素方式
            this.$refs[`list${a}`][0].$el.classList.add("el-button--primary");

            //原生dom方式
            // document.querySelector(`#list${a}`).classList.add("el-button--primary");
          }
        }
      });
    },
    //点击答题卡
    clickAnswerCard(index) {
      //切换到当前题目
      this.questionId = index;
      //关闭对话框
      this.dialogVisible = false;

      //如果当前题目已经被用户选择则显示用户选择的答案
      if (this.studentAnswer[index] != "") {
        this.radio = this.studentAnswer[index];
      }
    },
  },
  mounted() {
    //挂载阶段，发起axios请求
    //从题库获取题目
    axios
      .get("/v1/students/select")
      .then((result) => {
        if (result.data.status == 200) {
          this.question = result.data.data;
          // console.log(this.question);
        }
      })
      .catch((err) => {
        console.log(err);
      });
    this.startTime = new Date();
    //在当前时间this.startTime变量上加上2个小时，并将结果赋值给this.endTime变量
    this.endTime = this.startTime.setHours(this.startTime.getHours() + 2);
    this.endTime = new Date(this.endTime);
    this.examInit();
  },
  destroyed() {
    //离开当前组件就销毁
    window.onblur = null;
  },
};
</script>

<style lang="css">
[v-cloak] {
  display: none;
}
.card-header {
  padding: 10px;
  font-size: 20px;
  margin-top: 30px;
}
.answer-card {
  cursor: pointer;
}
.time,
.answer-card {
  margin-top: 10px;
}
.answer-item {
  padding: 10px;
}
.question {
  padding: 10px 0;
}
.card-content {
  width: 90%;
  margin: 0 auto;
  margin-top: 40px;
}

.card-content .box-card {
  min-height: 500px;
}

.el-button.stu-answer-item {
  margin: 10px;
  width: 60px;
  height: 60px;
}
</style>
